package com.wz.leetcode.linkedlist;


import com.wz.leetcode.linkedlist.ListNode;

/**
 * @author ：Mark老师
 * @description ：剑指Offer 22：链表中倒数第k个节点
 * 输入一个链表，输出该链表中倒数第k个节点。
 * 为了符合大多数人的习惯，本题从1开始计数，
 * 即链表的尾节点是倒数第1个节点。
 */
public class KthFromTail_Offer22 {

    public static ListNode kFromEnd(ListNode head , int k){
        if ( k <= 0 || head == null) return null;
        ListNode dummy = new ListNode(-1, head);
        ListNode fast = dummy, slow = dummy;
        /*(沿着链表)移动了k次*/
        for(int count = 1; count <= k; count++) {
            if (fast != null) {
                fast = fast.next;
            } else {
                return null;
            }
        }
        while(fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

    public static void main(String[] args) {
        ListNode test = new ListNode(6);
        test.setNext(new ListNode(0))
                .setNext(new ListNode(11))
                .setNext(new ListNode(8))
                .setNext(new ListNode(9))
                .setNext(new ListNode(5))
                .setNext(new ListNode(4))
                .setNext(new ListNode(1));
        System.out.println(kFromEnd(test,11));

    }

}
